﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Audio;

namespace Project
{

    class SpikeLauncher : GameEntity
    {

        private const long FIRE_INTERVAL = 1000; // fire every second
        private long timeSinceLastLaunch = 0;

        protected SpotLight light;

        protected Vector3 direction;

        private void shootSpikeBall(GameTime gt, GameState gs)
        {
            SpikeBall spikeBall = new SpikeBall(position, direction);
            gs.spawnEntity(spikeBall);
        }


        public SpikeLauncher(Vector3 position, Quaternion orientation)
            : base(position, orientation)
        {
            this.gravity = Vector3.Zero;
            this.maxSpeed = 0;

            collisionObject = new CollisionObject(
                new AABB(Vector3.Zero, Vector3.Zero, position),
                delegate(CollisionData data) { }, this
            );
        }

        public override void init(GameState gs)
        {
            base.init(gs);

            //look for candidate directions to launch the spiky ball
            Vector3[] possibleDirections = {
                new Vector3(1, 0, 0),
                new Vector3(-1, 0, 0),
                new Vector3(0, 1, 0),
                new Vector3(0, -1, 0),
                new Vector3(0, 0, 1),
                new Vector3(0, 0, -1)
            };
            foreach(Vector3 dir in possibleDirections) {
                AABB testBox = new AABB(
                    new Vector3(-0.1f, -0.1f, -0.1f), new Vector3(0.1f, 0.1f, 0.1f), (position + dir));
                if (!gs.getCollisionManager().map.collides(testBox))
                {
                    direction = dir;
                }
            }
            // direction = new Vector3(1, 0, 0);
            light = new SpotLight(
                -position, direction,
                new Color(1, 0.25f, 0.05f, 1),
                (float)Math.Cos(1.047), 0.1f, 0.3f, 0.3f);
            gs.getScene().spotLights.Add(light);
        }

        public override void destroy(GameState gs)
        {
            base.destroy(gs);
            gs.getScene().spotLights.Remove(light);
        }

        public override bool update(GameTime gt, GameState gs)
        {
            timeSinceLastLaunch += gt.ElapsedGameTime.Milliseconds;
            if (timeSinceLastLaunch > FIRE_INTERVAL)
            {
                timeSinceLastLaunch = 0;
                shootSpikeBall(gt, gs);
            }

            return base.update(gt, gs);
        }
    }
}
